import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mobile_vpn/common/cpn/cpn_view_state.dart';
import 'package:mobile_vpn/common/cpn/sliver_app_bar.dart';
import 'package:mobile_vpn/pages/set_up/version_page/version_logic.dart';
import 'package:package_info_plus/package_info_plus.dart';


import 'package:url_launcher/url_launcher.dart';

class VersionPage extends CpnViewState<VersionLogic> {
  VersionPage({Key? key}) : super(key: key, bindViewState: false);
  final RxString _version = ''.obs;
  final RxString _buildNumber = '1.0.1'.obs;
  final RxBool _isLatestVersion = true.obs;

  @override
  void initState() {

    _loadVersionInfo(); // 直接调用初始化方法
  }

  Future<void> _loadVersionInfo() async {
    final packageInfo = await PackageInfo.fromPlatform();
    _version.value  = packageInfo.version;
    _buildNumber.value  = packageInfo.buildNumber;
    // 这里添加版本检查逻辑
    // _isLatestVersion.value  = await controller.checkLatestVersion(_version.value);
  }

  Future<void> _checkUpdate() async {
    // 模拟检查更新
    Get.dialog(
      AlertDialog(
        title: Text(_isLatestVersion.value  ? '已是最新版本' : '发现新版本'),
        content: Text(_isLatestVersion.value
            ? '当前版本 $_version (${_buildNumber}) 已是最新'
            : '发现新版本 2.0.0，立即更新？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('取消'),
          ),
          if (!_isLatestVersion.value)
            TextButton(
              onPressed: () => _launchAppStore(),
              child: Text('更新'),
            ),
        ],
      ),
    );
  }

  Future<void> _launchAppStore() async {
    String url;
    if (Platform.isIOS)  {
      // iOS: 优先尝试 itms-apps 协议（深层链接）
      url = 'itms-apps://apps.apple.com/app/idYOUR_APP_ID';
    } else {
      // Android: 默认 Google Play，可扩展其他商店
      url = 'market://details?id=YOUR_PACKAGE_NAME';
    }

    try {
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        // 降级方案：打开网页版商店
        final fallbackUrl = Platform.isIOS
            ? 'https://apps.apple.com/app/idYOUR_APP_ID'
            : 'https://play.google.com/store/apps/details?id=YOUR_PACKAGE_NAME';
        if (await canLaunch(fallbackUrl)) {
          await launch(fallbackUrl);
        } else {
          throw '无法跳转';
        }
      }
    } catch (e) {
      Get.snackbar(' 错误', '无法打开应用商店: ${e.toString()}');
    }
  }

  @override
  Widget buildBody(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: CustomScrollView(
        slivers: [
          commonSliverAppBar(
            title: '版本信息',
          ),
          SliverPadding(
            padding: EdgeInsets.symmetric(horizontal:  24.w, vertical: 40.h),
            sliver: SliverList(
              delegate: SliverChildListDelegate([
                // 版本图标区域
                _buildVersionHeader(),
                SizedBox(height: 40.h),

                // 功能列表
                _buildFunctionList(),
                SizedBox(height: 60.h),

                // 版权信息
                _buildCopyrightInfo(),
              ]),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVersionHeader() {
    return Column(
      children: [
        // 应用图标
        Container(
          width: 120.w,
          height: 120.w,
          decoration: BoxDecoration(
            color: Colors.blue,
            borderRadius: BorderRadius.circular(24.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black12,
                blurRadius: 10,
                offset: Offset(0, 4),
              ),
            ],
          ),
          child: Icon(Icons.security,  size: 60.w, color: Colors.white),
        ),
        SizedBox(height: 20.h),

        // 版本信息
        Obx(() => Text(
          'Version $_version ${_buildNumber}',
          style: TextStyle(
            fontSize: 32.sp,
            color: Colors.grey[600],
          ),
        )),
        SizedBox(height: 8.h),

        // 更新状态
        Obx(() => Text(
          _isLatestVersion.value  ? '已是最新版本' : '有新版本可用',
          style: TextStyle(
            fontSize: 25.sp,
            color: _isLatestVersion.value  ? Colors.green  : Colors.orange,
          ),
        )),
      ],
    );
  }

  Widget _buildFunctionList() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 6,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          // 检查更新
          _buildListTile(
            icon: Icons.system_update,
            title: '检查更新',
            trailing: Icon(Icons.arrow_forward_ios,  size: 16.w),
            onTap: _checkUpdate,
          ),
          Divider(height: 1, indent: 16.w),

          // 版本历史
          _buildListTile(
            icon: Icons.history,
            title: '版本历史',
            trailing: Icon(Icons.arrow_forward_ios,  size: 16.w),
            onTap: () => Get.toNamed('/history'),
          ),
          Divider(height: 1, indent: 16.w),

          // 用户协议
          _buildListTile(
            icon: Icons.description,
            title: '用户协议',
            trailing: Icon(Icons.arrow_forward_ios,  size: 16.w),
            onTap: () => Get.toNamed('/agreement'),
          ),
          Divider(height: 1, indent: 16.w),

          // 隐私政策
          _buildListTile(
            icon: Icons.privacy_tip,
            title: '隐私政策',
            trailing: Icon(Icons.arrow_forward_ios,  size: 16.w),
            onTap: () => Get.toNamed('/privacy'),
          ),
        ],
      ),
    );
  }

  Widget _buildListTile({
    required IconData icon,
    required String title,
    Widget? trailing,
    VoidCallback? onTap,
  }) {
    return ListTile(
      leading: Icon(icon, color: Colors.blue),
      title: Text(title, style: TextStyle(fontSize: 25.sp)),
      trailing: trailing,
      onTap: onTap,
      contentPadding: EdgeInsets.symmetric(horizontal:  16.w),
      minLeadingWidth: 24.w,
    );
  }

  Widget _buildCopyrightInfo() {
    return Column(
      children: [
        Text(
          '© 2025 Mobile VPN',
          style: TextStyle(
            fontSize: 20.sp,
            color: Colors.grey[500],
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          'All Rights Reserved',
          style: TextStyle(
            fontSize: 20.sp,
            color: Colors.grey[500],
          ),
        ),
      ],
    );
  }
}